package cn.anquing.demo.mybatisplus.code.controller;


import cn.anquing.demo.mybatisplus.code.pojo.entity.Demo;
import cn.anquing.demo.mybatisplus.code.service.DemoService;
import com.fasterxml.jackson.datatype.jdk8.OptionalLongDeserializer;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wqq
 * @since 2021-04-18
 */
@RestController
@RequestMapping("/demo")
public class DemoController {

    @Resource
    private DemoService demoService;

    /**
     * 查询所有数据
     * @author wangquanqing
     * @date 2021/4/18 10:33
     * @param
     * @return java.lang.Object
     */
    @GetMapping("/list")
    public Object list(){
        return demoService.list();
    }

    /**
     * 新增一条数据
     * @author wangquanqing
     * @date 2021/4/18 10:33
     * @param
     * @return java.lang.Object
     */
    @PostMapping("/")
    public Object add(){
        Demo demo = Demo.builder()
                .name("名字" + RandomUtils.nextInt())
                .build();
        return demoService.save(demo);
    }

    /**
     * 更新一条数据
     * @author wangquanqing
     * @date 2021/4/18 10:33
     * @param
     * @return java.lang.Object
     */
    @PutMapping("/{id}")
    public Object update(@PathVariable("id") Integer id){
        Demo oldDemo = demoService.getById(id);
        if (oldDemo != null) {
            oldDemo.setName("名字" + RandomUtils.nextInt());
            demoService.updateById(oldDemo);
            return "更新成功";
        }

        return "数据不存在，更新失败";
    }

    /**
     * 删除一条数据
     * @author wangquanqing
     * @date 2021/4/18 10:33
     * @param
     * @return java.lang.Object
     */
    @DeleteMapping("/{id}")
    public Object delete(@PathVariable("id") Integer id){
        Demo demo = demoService.getById(id);
        if (demo != null) {
            demoService.removeById(id);
            return "删除成功";
        }
        return "数据不存在";
    }

}

